using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace Voodoo.Sauce.Core
{
	public static class TransactionUtility
	{
		private const string PURCHASE_ID_PREFIX_KEY = "PurchaseId_";

		public static string GetProductKey(string productId)
		{
			return "PurchaseId_" + productId;
		}

		public static string GetPurchaseUniqueId(string productId, bool generate)
		{
			string productKey = GetProductKey(productId);
			if (generate)
			{
				return GeneratePurchaseId(productKey);
			}
			Stack<string> purchaseIds = GetPurchaseIds(productKey);
			if (purchaseIds.Count <= 0)
			{
				return "";
			}
			return purchaseIds.Peek();
		}

		private static string GeneratePurchaseId(string productKey)
		{
			string text = Guid.NewGuid().ToString();
			Stack<string> purchaseIds = GetPurchaseIds(productKey);
			purchaseIds.Push(text);
			SavePurchaseIds(purchaseIds, productKey);
			return text;
		}

		public static string DeletePurchaseId(string productId)
		{
			string result = "";
			string productKey = GetProductKey(productId);
			Stack<string> purchaseIds = GetPurchaseIds(productKey);
			if (purchaseIds.Count > 0)
			{
				result = purchaseIds.Pop();
				SavePurchaseIds(purchaseIds, productKey);
			}
			return result;
		}

		private static void SavePurchaseIds(Stack<string> purchaseIds, string productKey)
		{
			if (purchaseIds.Count == 0)
			{
				NintendoPlayerPrefs.DeleteKey(productKey);
				return;
			}
			List<string> list = purchaseIds.ToList();
			list.Reverse();
			string value = JsonConvert.SerializeObject(list);
			NintendoPlayerPrefs.SetString(productKey, value);
		}

		private static Stack<string> GetPurchaseIds(string productKey)
		{
			string @string = NintendoPlayerPrefs.GetString(productKey, "");
			if (string.IsNullOrEmpty(@string))
			{
				return new Stack<string>();
			}
			return new Stack<string>(JsonConvert.DeserializeObject<List<string>>(@string));
		}
	}
}
